//
//  OAuthViewController.swift
//  sinaOnceAgain
//
//  Created by 王相超 on 16/2/18.
//  Copyright © 2016年 chuanzhi. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    
    
    let webView = UIWebView()
    
    //点击事件
    @objc private func close() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func testAccount() {
        
        //本地代码  和  webview 的交互
        let jsString = "document.getElementById('userId').value = 'q938239088@qq.com' , document.getElementById('passwd').value  = '68866886wang' "
        //通过一个字符串对象来执行 javascript代码
         webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    
    override func loadView() {
        
        view = webView
        
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试帐号", style: .Plain, target: self, action: "testAccount")
        
        //使用webView加载授权页面
        loadOauthPage()
    }
    
    //在页面将要消失的时候  dismiss
    override func viewDidDisappear(animated: Bool) {
        
        super.viewDidDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    private func loadOauthPage() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id="+client_id+"&redirect_uri="+redirect_uri
        
        let url = NSURL(string: urlString)!
        
        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
    }
    
}


//扩展   专门处理webview的协议方法
extension OAuthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        //开启指示器
        SVProgressHUD.show()
    }
    
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        //关闭指示器
        SVProgressHUD.dismiss()
    }
    
    //获取授权成功后的code
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print(request.URL)
        
        guard let urlString = request.URL?.absoluteString else{
            
            return false
        }
        
        //判断是否包含  code
        if urlString.containsString("code") {
            
            //截取对应的字符串
            guard let query = request.URL?.query else {
                
                return false
            }
            
            let codeStr = "code="
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            
            //用code换取 token
            UserAccountViewModel.sharedAccountViewModel.loadAccessToken(code, finished: { (isSuccess) -> () in
                
                //登录成功
                if isSuccess {
                    
                    self.dismissViewControllerAnimated(true, completion: nil)
                    //登录成功之后  将视图控制器设为  欢迎页面
                     NSNotificationCenter.defaultCenter().postNotificationName(KChoseRootVC, object: nil)
                    
                }else {
                    
                    SVProgressHUD.showErrorWithStatus("登录失败,请检查网络")
                }
                
            })
            
            return false
        }
        
        return true
    }
    
}

